package xian.woniu.service.impl;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xian.woniu.entity.User;
import xian.woniu.entity.User;
import xian.woniu.entity.UserExample;
import xian.woniu.mapper.UserMapper;
import xian.woniu.service.IUserService;

import java.util.List;
import xian.woniu.service.IUserService;

/**
 * @author SongHang
 * @time 2022/06/29 16:12:58
 */
@Service
@Transactional
public class UserServiceImpl implements IUserService {

    private UserMapper userMapper;

    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }


    @Override
    public User login(String userName, String userPassword) {
        UserExample userExample=new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUsernameEqualTo(userName);
        criteria.andPasswordEqualTo(userPassword);
        List<User> users = userMapper.selectByExample(userExample);
        if(users==null||users.size()==0){
            return null;
        }
        return users.get(0);
    }

    @Override
    public Integer regist(User user) {

        String username = user.getUsername();
        String password = user.getPassword();
        Integer flag = user.getFlag();


        //查询有无重复用户名，密码校验通过前端来判断。
        UserExample userExample=new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUsernameEqualTo(username);

        List<User> users = userMapper.selectByExample(userExample);

        if(users.size()!=0){
            return -1;
        }

        User user1=new User();

        user1.setUsername(username);
        user1.setPassword(password);
        user1.setFlag(flag);

        userMapper.insert(user1);


        return user1.getUid();
    }

    @Override
    public List<User> findAll() {
        return userMapper.selectByExample(null);
    }

    @Override
    public List<User> findByFlag(Integer flag) {
        UserExample userExample=new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andFlagEqualTo(flag);
        return userMapper.selectByExample(userExample);
    }

    @Override
    public void updateFlag(User user) {
        User user1 = user;
        user1.setFlag(4);
        userMapper.updateByPrimaryKeySelective(user1);
    }

    @Override
    public void updateUser(User user) {
        User user1 = user;
            user1.setFlag(2);
            userMapper.updateByPrimaryKeySelective(user1);

    }
}
